package com.openxt.nbzj.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.merhold.extensiblepageindicator.ExtensiblePageIndicator;
import com.morgoo.droidplugin.pm.PluginManager;
import com.openxt.nbzj.R;
import com.openxt.nbzj.activity.EnterpriseCreditTypeActivity;
import com.openxt.nbzj.activity.EnterpriseGetNativeActivity;
import com.openxt.nbzj.activity.HomeActivity;
import com.openxt.nbzj.activity.JWGWActivity;
import com.openxt.nbzj.activity.LoginActivity;
import com.openxt.nbzj.activity.NewsListActivity;
import com.openxt.nbzj.activity.NoticeActivity;
import com.openxt.nbzj.activity.ProjectActivity;
import com.openxt.nbzj.activity.WebViewActivity;
import com.openxt.nbzj.adapter.ViewPagerAdapter;
import com.openxt.nbzj.model.ConfigModel;
import com.openxt.nbzj.model.RemotingModel;
import com.openxt.nbzj.plugins.AppPlugins;
import com.openxt.nbzj.remoting.RemotingEx;
import com.openxt.nbzj.util.App;
import com.openxt.nbzj.util.SystemUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import qs.openxt.libs.fragment.ConfirmDialogListener;
import qs.openxt.libs.progress.Wait;
import qs.openxt.libs.remoting.Download;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;

/**
 * Created by 颖杰_2 on 2016/5/31.
 */
public class ContentPartsFragment extends OpenxtFragment implements View.OnClickListener, RemotingEx.OnActionListener {
    @BindView(R.id.widget)
    LinearLayout widget;
    @BindView(R.id.widget0)
    LinearLayout widget0;
    @BindView(R.id.line_down_img)
    ImageView line_down_img;
    @BindView(R.id.activity)
    FrameLayout activityView;
    @BindView(R.id.viewPagerMain)
    ViewPager mViewPagerMain;
    @BindView(R.id.flexibleIndicatorMain)
    ExtensiblePageIndicator extensiblePageIndicatorMain;

    ViewPagerAdapter activityViewPagerAdapter = null;

    RemotingModel remotingModel = null;
    Handler mHandler = new Handler();
    Context mContext;
    List<OpenxtFragment> mList = new ArrayList<>();
    HomeFragment homeFragment;
    boolean first_more = false;

    public void setHomeFragment(HomeFragment homeFragment) {
        this.homeFragment = homeFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content_item_parts, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext = getActivity();
        remotingModel = new RemotingModel(mContext);

        activityViewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
        activityViewPagerAdapter.setList(mList);
        mViewPagerMain.setAdapter(activityViewPagerAdapter);
        extensiblePageIndicatorMain.initViewPager(mViewPagerMain);
        line_down_img.setOnClickListener(this);

        initView();
    }

    private void initView() {
        initSubscription();
        initActivityGet();

        if (ActivityUtil.isNetworkAvailable(mContext)) {
            remotingModel.getActivityGet(this, false);
        }
    }

    private void initSubscription() {
        try {
            JSONArray data = SystemUtil.getSubscribeList(mContext);
            JSONArray array = new JSONArray();
            if (RemotingModel.isLogin()) {
                String val = Utils.getLocalStorage(mContext, ConfigModel.LOGIN_NATIVE);
                JSONObject info = JSON.parseObject(val);
                JSONArray Subscribed = null;//已订阅部分
                JSONArray IDENTITIES = info.getJSONArray("IDENTITIES");
                for (int i = 0, j = IDENTITIES.size(); i < j; i++) {
                    JSONObject item = IDENTITIES.getJSONObject(i);
                    if ("63".equals(item.getString("APPID")) && item.getBooleanValue("ISMR")) {
                        Subscribed = item.getJSONArray("SUBED");
                        break;
                    }
                }
                if (Subscribed == null)
                    Subscribed = new JSONArray();
                Map<Long, JSONObject> map = ConfigModel.getSubscribes(mContext);
                for (int i = 0, j = Subscribed.size(); i < j; i++) {
                    Long ID = Subscribed.getLong(i);
                    JSONObject item = map.get(ID);
                    if (item != null)
                        array.add(ID);
                }
            } else {
                for (int i = 0, j = data.size(); i < j; i++) {
                    JSONObject item = data.getJSONObject(i);
                    boolean IsDefault = item.getBoolean("IsDefault");
                    if (IsDefault) {
                        array.add(item.getLong("ID"));
                    }
                }
            }
            int len = array.size();
            int size = (int) Math.ceil(Double.valueOf(len) / 4);

            //第一页显示12条 之后显示在第二页中
            LayoutInflater inflater = LayoutInflater.from(mContext);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, SystemUtil.dip2Px(80f, mContext), 1.0f);
            //第一页
            widget.removeAllViews();
            widget0.removeAllViews();

            first_more = false;
            LinearLayout.LayoutParams _params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
            for (int i = 0, k = 3; i < k; i++) {
                LinearLayout l = new LinearLayout(mContext);
                l.setLayoutParams(params);
                l.setOrientation(LinearLayout.HORIZONTAL);
                for (int j = 0; j < 4; j++) {
                    Long ID = null;
                    try {
                        ID = array.getLong(i * 4 + j);
                    } catch (Exception e) {
                        ID = null;
                    }
                    LinearLayout _child = getChildItem(ID, inflater, _params);
                    l.addView(_child);
                }
                widget.addView(l);
            }
            widget.invalidate();

            if (size < 4)
                size = 4;
            for (int i = 3, k = size; i < k; i++) {
                LinearLayout l = new LinearLayout(mContext);
                l.setLayoutParams(params);
                l.setOrientation(LinearLayout.HORIZONTAL);
                for (int j = 0; j < 4; j++) {
                    Long ID = null;
                    try {
                        ID = array.getLong(i * 4 + j);
                    } catch (Exception e) {
                        ID = null;
                    }
                    LinearLayout _child = getChildItem(ID, inflater, _params);
                    l.addView(_child);
                }
                widget0.addView(l);
            }
            if (!first_more) {
                LinearLayout l = new LinearLayout(mContext);
                l.setLayoutParams(params);
                l.setOrientation(LinearLayout.HORIZONTAL);
                for (int j = 0; j < 4; j++) {
                    LinearLayout _child = getChildItem(9999999L, inflater, _params);
                    l.addView(_child);
                }
                widget0.addView(l);
            }
            widget0.invalidate();
        } catch (Exception e) {
            Log.d("a", e.getMessage());
        }
    }

    private LinearLayout getChildItem(Long ID, LayoutInflater inflater, LinearLayout.LayoutParams _params) throws Exception {
        JSONObject item = ConfigModel.getSubscribes(mContext).get(ID);
        LinearLayout _child = null;
        if (item == null) {
            _child = (LinearLayout) inflater.inflate(R.layout.item_more, null);
            _child.setLayoutParams(_params);
            _child.setEnabled(false);
            if (!first_more) {
                _child.setEnabled(true);
                _child.setTag("$more$");
                _child.setOnClickListener(this);
                View item_iv = _child.findViewById(R.id.item_iv);
                item_iv.setVisibility(View.VISIBLE);
            }
            first_more = true;
        } else {
            item = JSON.parseObject(item.toString());
            String IconURL = item.getString("IconURL");
            String Name = item.getString("Name");
            _child = (LinearLayout) inflater.inflate(R.layout.item, null);
            _child.setLayoutParams(_params);
            _child.setTag(item);
            _child.setOnClickListener(this);
            ImageView item_iv = (ImageView) _child.findViewById(R.id.item_iv);
            item_iv.setImageBitmap(SystemUtil.getImageFromAssetsFile(IconURL, getActivity()));
            TextView item_tv = (TextView) _child.findViewById(R.id.item_tv);
            item_tv.setText(Name);
        }
        return _child;
    }

    private void initActivityGet() {
        String val = Utils.getLocalStorage(getActivity(), ConfigModel.ACTIVITY_GET);
        if (StringUtil.isNull(val))
            return;
        try {
            final JSONArray data = JSON.parseArray(val);
            if (data.size() == 0) {
                activityView.setVisibility(View.GONE);
                return;
            }
            activityView.setVisibility(View.VISIBLE);
            mList.clear();
            activityViewPagerAdapter.notifyDataSetChanged();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0, j = data.size(); i < j; i++) {
                        JSONObject item = data.getJSONObject(i);
                        String IMGURL = item.getString("IMGURL");
                        if (StringUtil.isNull(IMGURL))
                            continue;
                        ActivityFragment f = new ActivityFragment();
                        f.setJSON(item);
                        mList.add(f);
                    }
                    activityViewPagerAdapter.notifyDataSetChanged();
                    if (mList.size() == 1)
                        extensiblePageIndicatorMain.setVisibility(View.GONE);
                    else
                        extensiblePageIndicatorMain.initViewPager(mViewPagerMain);
                }
            }, 0);
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.line_down_img) {
            homeFragment.setCurrentItem(0);
            return;
        }

        Object tag = v.getTag();
        if (tag instanceof String) {
            String more = (String) tag;
            if ("$more$".equals(more)) {
                if (!RemotingModel.isLogin()) {
                    showMsg("请先登录");
                    toActivityForResult(LoginActivity.class, null, App.LOGIN);
                    return;
                }

                ((HomeActivity) getActivity()).setCurrentItem(1);
            }
        } else if (tag instanceof JSONObject) {
            JSONObject item = (JSONObject) tag;
            if (item.getBoolean("IsNative")) {
                String RedirectURL = item.getString("RedirectURL");
                if ("#/newslist".equals(RedirectURL)) {
                    toActivity(NewsListActivity.class);
                } else if ("#/enterprice".equals(RedirectURL)) {
                    toActivity(EnterpriseGetNativeActivity.class);
                } else if ("#/enterpricecredit".equals(RedirectURL)) {
                    toActivity(EnterpriseCreditTypeActivity.class);
                } else if ("#/project".equals(RedirectURL)) {
                    toActivity(ProjectActivity.class);
                } else if ("#/noticelist".equals(RedirectURL)) {
                    toActivity(NoticeActivity.class);
                } else if ("#/jwgw".equals(RedirectURL)) {
                    toActivity(JWGWActivity.class);
                } else {
                    try {
                        final AppPlugins.Plugin plugin = AppPlugins.getPlugin(RedirectURL);
                        if (plugin == null)
                            return;
                        if (PluginManager.getInstance().isPluginPackage(plugin.getPackageName())) {
                            PackageInfo packageInfo = PluginManager.getInstance().getPackageInfo(plugin.getPackageName(), 0);
                            if (!plugin.getVersion().equals(packageInfo.versionName)) {
                                String tip = plugin.getName() + "检测到新版本，确认更新？";
                                ActivityUtil.showConfirmDialog(mContext, tip, "使用新版本", "继续旧版本", new ConfirmDialogListener() {
                                    @Override
                                    public void onOK() {
                                        doDownLoadPlugin(plugin.getPackageName(), mContext, plugin.getUrl(), true);
                                    }

                                    @Override
                                    public void onCancel() {
                                        openPlugin(plugin.getPackageName());
                                    }
                                });
                            } else {
                                //PluginManager.getInstance().deletePackage(plugin.getPackageName(), 0);
                                openPlugin(plugin.getPackageName());
                            }
                        } else {
                            String tip = plugin.getName() + "尚未安装，需下载";
                            ActivityUtil.showConfirmDialog(mContext, tip, "下载安装", "下次再说", new ConfirmDialogListener() {
                                @Override
                                public void onOK() {
                                    doDownLoadPlugin(plugin.getPackageName(), mContext, plugin.getUrl(), false);
                                }

                                @Override
                                public void onCancel() {

                                }
                            });
                        }
                    } catch (Exception e) {
                        Log.d("TAG", e.getMessage());
                    }
                }
            } else {
                if (!ActivityUtil.isNetworkAvailable(mContext)) {
                    showMsg("无网络，请先查看网络是否正常打开");
                    return;
                }
                if ("true".equals(item.getString("AccessHasLogin")) && !RemotingModel.isLogin()) {
                    showMsg("请先登录");
                    toActivityForResult(LoginActivity.class, null, App.LOGIN);
                    return;
                }
                Utils.setLocalStorage(mContext, ConfigModel.NATIVE_PAGENAME, getActionUrl());
                Bundle bundle = new Bundle();
                bundle.putString("url", ConfigModel.ROOTPATH + item.getString("RedirectURL"));
                toActivity(WebViewActivity.class, bundle, false);
            }
        }
    }

    @Override
    public void refresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initSubscription();
            }
        }, 0);
    }

    @Override
    public void willBeDisplayed() {

    }

    @Override
    public void onActionCompleted(String reVal, String actionName) {
        Utils.setLocalStorage(getActivity(), actionName, reVal);
        if (ConfigModel.ACTIVITY_GET.equals(actionName)) {
            initActivityGet();
        }
    }

    @Override
    public void onActionFailed(String errorVal, String actionName) {

    }

    private void doDownLoadPlugin(final String pluginName, final Context context, String url, final boolean update) {
        Download download = new Download(context, url, new Download.OnActionListener() {
            @Override
            public void onActionCompleted(String path) {
                Wait.sharedInstance().start(mContext, "正在安装应用..., 请稍候");
                Tx tx = new Tx();
                tx.execute(new String[]{path, pluginName});
            }

            @Override
            public void onActionError(String error) {
                Toast.makeText(context, error, Toast.LENGTH_LONG).show();
            }
        });
        download.doRequest();
    }

    private void openPlugin(String packageName) {
        Wait.sharedInstance().stopAll();
        PackageManager pm = mContext.getPackageManager();
        Intent intent = pm.getLaunchIntentForPackage(packageName);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("login_config", Utils.getLocalStorage(mContext, ConfigModel.LOGIN_NATIVE));
        mContext.startActivity(intent);
    }

    private class Tx extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... params) {
            String path = params[0];
            String pluginName = params[1];
            try {
                PluginManager.getInstance().deletePackage(pluginName, 0);
                PluginManager.getInstance().installPackage(path, 0);
                openPlugin(pluginName);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }
    }
}
